package com.fg.cloud.manager.service.product.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.manager.entry.BaseEntity;
import com.fg.cloud.manager.entry.product.ProductInfoEntity;
import com.fg.cloud.manager.entry.product.ProductMoreUnitEntity;
import com.fg.cloud.manager.entry.product.ProductParamEntity;
import com.fg.cloud.manager.entry.product.ProductSkuEntity;
import com.fg.cloud.manager.entry.product.vo.ProductInfoVo;
import com.fg.cloud.manager.entry.product.vo.ProductMoreUnitVo;
import com.fg.cloud.manager.entry.product.vo.ProductSkuVo;
import com.fg.cloud.manager.mapper.BaseMapper;
import com.fg.cloud.manager.mapper.agency.AgencyCartMapper;
import com.fg.cloud.manager.mapper.agency.AgencyProductMapper;
import com.fg.cloud.manager.mapper.product.ProductInfoMapper;
import com.fg.cloud.manager.mapper.product.ProductMoreUnitMapper;
import com.fg.cloud.manager.mapper.product.ProductParamMapper;
import com.fg.cloud.manager.mapper.product.ProductSkuImgMapper;
import com.fg.cloud.manager.mapper.product.ProductSkuMapper;
import com.fg.cloud.manager.service.BaseServiceImpl;
import com.fg.cloud.manager.service.product.ProductInfoService;

@Service
public class ProductInfoServiceImpl extends BaseServiceImpl implements ProductInfoService{

	@Autowired
	private ProductInfoMapper productMapper ;
	@Autowired
	private ProductSkuMapper skuMapper ;
	@Autowired
	private ProductSkuImgMapper imgMapper ; 
	@Autowired
	private ProductParamMapper paramMapper ;
	@Autowired
	private ProductMoreUnitMapper pro_moreUnitMapper;
	@Autowired
	private AgencyProductMapper agencyProductMapper;
	@Autowired
	private AgencyCartMapper cartMapper ;
	
	
	@Override
	protected <T extends BaseEntity> BaseMapper getBaseMapper() {
		return productMapper;
	}
	
	/**
	 * 商品数据重置
	 */
	@Override
	@Transactional
	public boolean deleteProduct(Long facId) {
		//删除经销商订货权限、经销商特价管理
		StringBuffer sb = new StringBuffer("t_agency_product_");
		sb.append(facId);
		long r1 = agencyProductMapper.delByfacId(sb.toString(), facId);
		//删除商品参数
		long r2 = paramMapper.delByfacId(facId);
		//删除商品多单位
		long r3 = pro_moreUnitMapper.delByfacId(facId);
		//删除商品图册
		long r4 = imgMapper.delByfacId(facId);
		//删除商品详情
		long r5 = skuMapper.delByfacId(facId);
		//删除商品信息
		long r6 = productMapper.delByfacId(facId);
		
		if ( r1>0 && r2>0 && r3>0 && r4>0 && r5>0 && r6>0 ) return true;

		return false;
	}
	
	/**
	 * 商品上下架
	 */
	@Override
	@Transactional
	public int productUpperAndLower(String ids, int isGround) {
		int result = productMapper.productUpperAndLower(ids, isGround);
		return result;
	}

	/**
	 * 通过商品名称查询商品信息。
	 */
	@Override
	public ProductInfoEntity getProductByName(String productName, Long facId) {
		return productMapper.selectByName(productName, facId);
	}

	/**
	 * 多条件模糊搜索商品
	 */
	@Override
	public List<ProductSkuEntity> selectByCondition(PageUtils<ProductSkuEntity> pageinfo) {
		List<ProductSkuEntity> skuList = productMapper.selectByCondition(pageinfo);
		findMoreUnit(skuList, pageinfo.getFacId());
		return skuList;
	}

	/**
	 * 高级搜索
	 */
	public List<ProductSkuEntity> advSearch(PageUtils<ProductSkuEntity> pageinfo) {
		List<ProductSkuEntity> skuList = productMapper.advSearch(pageinfo);
		findMoreUnit(skuList, pageinfo.getFacId());
		return skuList;
	}
	
	/**
	 * Description:封装多单位到商品详情
	 * @param skuList
	 * @param facId
	 * @author around
	 * @date 2017年9月11日下午4:29:09
	 */
	private void findMoreUnit(List<ProductSkuEntity> skuList, Long facId) {
		List<ProductMoreUnitVo> moreUnitList = null;
		StringBuffer moreUnitStr = new StringBuffer();
		for (ProductSkuEntity sku : skuList) {
			/*moreUnitList = Lists.newArrayList();
			moreUnitList.add(ProductMoreUnitVo.getProductMoreUnitVo(sku.getProductUnit(), 
					sku.getUnitName(), 1));
			moreUnitList.addAll(pro_moreUnitMapper.findList(facId, sku.getId()));*/
			moreUnitList = pro_moreUnitMapper.findList(facId, sku.getId());
			moreUnitStr.append(sku.getUnitName()).append("/");
			for (int i = 0; i < moreUnitList.size(); i++)
				moreUnitStr.append(moreUnitList.get(i).getLongName()).append("/");
				
			sku.setMoreUnitList(moreUnitList);
			moreUnitStr.deleteCharAt(moreUnitStr.lastIndexOf("/"));
			sku.setMoreUnitContent(moreUnitStr.toString());
			moreUnitStr.setLength(0);
		}
	}
	
	/**
	 * 逻辑删除商品
	 */
	@Override
	@Transactional
	public Result deleteProduct(Long productId,Long skuId,boolean isDelProduct)throws ServiceException  {
		int  result = 0 ;
		if(isDelProduct){ //删除SKU对应的商品信息
			List<ProductSkuEntity> skuIds = skuMapper.selectByProId(productId);
			if(skuIds != null && skuIds.size() > 0 ){
				for(ProductSkuEntity sku : skuIds){
					imgMapper.deleteBySkuId(sku.getId());
					result = skuMapper.deleteSku(skuId);
				}
			}
			result = productMapper.deleteProduct(productId);
			List<ProductParamEntity> paramList = paramMapper.selectByProductId(productId);
			if(paramList != null && paramList.size() > 0 ){
				result = paramMapper.deleteByProductId(productId);
			}
			cartMapper.deleteByproduct(productId);
		}else{
			ProductSkuEntity sku = skuMapper.find(skuId);
			if(sku != null && sku.getIsDefault().longValue() == 1 ){
				return  Result.result(null, false, StatusCode.REMOVEERROR, "商品默认规格不允许删除");
			}
			result = skuMapper.deleteSku(skuId);
			cartMapper.deleteBySkuId(skuId);
			if(result==0){
				result = imgMapper.deleteBySkuId(skuId);
			}
			List<ProductSkuEntity> skuList = skuMapper.selectByProId(productId);
			if(skuList.size() == 0 ){
				result = productMapper.deleteProduct(productId);
				cartMapper.deleteByproduct(productId);
			}
		}
		return  Result.result(null, true, StatusCode.REMOVESUCCESS, "商品信息删除成功");
	}

	/**
	 * 获取查询结果条目数
	 */
	@Override
	public Long count(PageUtils<ProductSkuEntity> pageinfo) {
		return productMapper.count(pageinfo);
	}

	/**
	 * 获取搜索框查询结果条目数
	 */
	@Override
	public Long countTop(PageUtils<ProductSkuEntity> pageinfo) {
		return productMapper.countTop(pageinfo);
	}

	@Transactional
	public Result addProduct(ProductInfoEntity productEntity,Long facId) throws ServiceException {
		List<ProductMoreUnitVo> moreUnitList = null;
		if(productEntity == null || StringUtils.isEmpty(productEntity.getProductName())
				||productEntity.getProductCategory()== null || productEntity.getProductCategory() < 0 ){
			throw new ServiceException(713, "商品名称、商品分类不能为空");
		}
		int flag = 0 ;
		ProductInfoEntity resEntity = productMapper.selectByName(productEntity.getProductName(), facId);
		if(resEntity != null ) {
			throw new ServiceException(751, "已经存在相同商品或相同商品名的产品");
		}
		List<ProductSkuEntity> skuList = productEntity.getSkuList();
		boolean judgeSku = judgeSku(skuList);
		if(!judgeSku){
			throw new ServiceException(StatusCode.LACKVALUE, "商品单位、编码、名称不能为空");
		}
		productEntity.setCreator(((BaseEntity)UserUtils.getCurrentUser()).getId());
		productEntity.setCreateTime(new Date());
		flag = productMapper.insert(productEntity);
		if(flag == 0){
			throw new ServiceException(StatusCode.EXCEPTIONERROR, ResultType.ADD_FAULT);
		}
		for(ProductSkuEntity skuInfo : skuList){
			List<ProductSkuEntity> sku = productMapper.selectByProductNumber(skuInfo.getProductNumber(), productEntity.getFacId(),
					null);
			if( sku.size() > 0){
				throw new ServiceException(StatusCode.DUPLICATIONERROR, "商品编码：‘"+skuInfo.getProductNumber()+"’已存在");
			}
			String spec = skuInfo.getProductSpec();
			spec = spec.replace("{", "");
			spec = spec.replace("}", "");
			spec = spec.replace("\"", "");
			skuInfo.setProductSpec(spec);
			skuInfo.setProductId(productEntity.getId());
			skuInfo.setProductName(productEntity.getProductName());
			skuInfo.setProductCategory(productEntity.getProductCategory());
			skuInfo.setFacId(productEntity.getFacId());
			if(String.valueOf(productEntity.getPrecision()) != null ){
				skuInfo.setPrecision(productEntity.getPrecision());
			}
			flag = skuMapper.insert(skuInfo);
			
			//添加多单位skuInfo.getMoreUnit();
			if (1 == skuInfo.getMultiUnit()) {
				if (null == skuInfo.getId()) {
					throw new ServiceException(StatusCode.SAVEERROR, "未填写商品详细信息");
				}
				moreUnitList = skuInfo.getMoreUnitList();
				for(int i = 0 ; i < moreUnitList.size() ; i ++ ){
					ProductMoreUnitEntity unit = moreUnitList.get(i);
					if(unit.getUnitId() == null ){
						moreUnitList.remove(i);
					}
				}
				pro_moreUnitMapper.batchDelete(facId, skuInfo.getId());
				pro_moreUnitMapper.batchInsert(facId, skuInfo.getId(), moreUnitList);
			}
			if(flag == 0 ){
				throw new ServiceException(StatusCode.SAVEERROR, "规格信息输入有误");
			}
		}
		//多图片处理
		List<String> imgList =productEntity.getImgList();
		if(imgList != null&& imgList.size() > 0){
			imgMapper.batchInsert(productEntity.getId(), imgList);
		}
		List<ProductParamEntity> paramList =productEntity.getParamList();
		if(paramList != null && paramList.size() > 0){
			for(ProductParamEntity param : paramList){
				param.setProductId(productEntity.getId());
				flag = paramMapper.insert(param);
				if(flag == 0 ) {
					throw new ServiceException(722, "保存商品参数失败");
				}
			}
		}
		return Result.result(null, true, StatusCode.SAVESUCCESS, "商品详情信息保存成功");
	}
	
	
	/**
	  * Description:判断商品详情的必填字段
	  * @param skuList 商品详情列表
	  * @return
	  * @author liushengchao
	  * @date 2017年8月16日下午6:20:31
	 */
	public boolean judgeSku(List<ProductSkuEntity> skuList ){
		if(skuList != null && skuList.size() > 0){
			for(ProductSkuEntity skuInfo : skuList){
				if(StringUtils.isEmpty(skuInfo.getProductNumber()) || skuInfo.getProductUnit()==null
						|| skuInfo.getProductUnit() < 0 )
				{
					return false;
				}
				return true ;
			}
		}
		return false;
	}

	@Override
	@Transactional
	public Result modifyProduct(ProductInfoEntity product,
			Long facId) throws ServiceException {
		int flag = 0 ;
		List<ProductMoreUnitVo> moreUnitList = null;
		if(product == null || StringUtils.isEmpty(product.getProductName())
				|| product.getProductCategory() < 0
				|| product.getId()== null || product.getId() < 0 ){
			throw new ServiceException(StatusCode.LACKVALUE,"商品名称,商品分类不能为空");
		}
		List<ProductSkuEntity> skuList = product.getSkuList();
		boolean judgeSku = judgeSku(skuList);
		if(!judgeSku) {
			throw new ServiceException(StatusCode.LACKVALUE,"商品单位、编码、名称不能为空");
		}
		
		List<ProductSkuEntity> list = skuMapper.selectByProId(product.getId());
		Long defaultSkuId = null ;
		for(ProductSkuEntity entity : list){
			if(entity.getIsDefault() == 0 ) continue ;
			defaultSkuId = entity.getId();
		}
		if(defaultSkuId == null ){
			throw new ServiceException(StatusCode.EXCEPTIONERROR, "商品没有默认规格");
		}
		for(ProductSkuEntity sku : skuList){
			String spec = sku.getProductSpec();
			spec = spec.replace("{", "");
			spec = spec.replace("}", "");
			spec = spec.replace("\"", "");
			sku.setProductSpec(spec);
			sku.setFacId(facId);
			sku.setProductCategory(product.getProductCategory());
			sku.setProductName(product.getProductName());
			if(null == sku.getId()){
				List<ProductSkuEntity> sku1 = productMapper.selectByProductNumber(sku.getProductNumber(), product.getFacId(),
						null);
				if( sku1.size() > 0){
					throw new ServiceException(StatusCode.DUPLICATIONERROR, "商品编码：‘"+sku.getProductNumber()+"’已存在");
				}
				sku.setProductId(product.getId());
				flag = skuMapper.insert(sku);
				if(sku.getIsDefault() == 1 ){
					flag = skuMapper.batchUpdate(sku.getId(), product.getId());
				}
			}else{
				if(sku.getId().longValue() == defaultSkuId.longValue() && sku.getIsDefault() == 0  && skuList.size() == 1){
					throw new ServiceException(StatusCode.LACKVALUE, "商品"+product.getProductName()+"必须设置默认规格");
				}
				flag = skuMapper.update(sku);
				if(sku.getIsDefault() == 1  && sku.getId().longValue() != defaultSkuId.longValue()){
					flag = skuMapper.batchUpdate(sku.getId(), product.getId());
					if(flag == 0 ){
						throw new ServiceException(StatusCode.EXCEPTIONERROR, "修改失败");
					}
				}
			}
			//添加多单位skuInfo.getMoreUnit();
			if (1 == sku.getMultiUnit()) {
				if (null == sku.getId()) {
					throw new ServiceException(StatusCode.SAVEERROR, "未填写商品详细信息");
				}
				moreUnitList = sku.getMoreUnitList();
				for(int i = 0 ; i < moreUnitList.size() ; i ++ ){
					ProductMoreUnitEntity unit = moreUnitList.get(i);
					if(unit.getUnitId() == null ){
						moreUnitList.remove(i);
					}
				}
				pro_moreUnitMapper.batchDelete(facId, sku.getId());
				pro_moreUnitMapper.batchInsert(facId, sku.getId(), moreUnitList);
			} else {
				pro_moreUnitMapper.batchDelete(facId, sku.getId());
			}
		}
		
		List<String> imgList =product.getImgList();
		List<String> selImgList = imgMapper.selectByProductId(product.getId());
		if(selImgList != null && selImgList.size() > 0 ){
			flag = imgMapper.deleteByProductId(product.getId());
		}
		if(flag == 0){
			throw new ServiceException(StatusCode.EXCEPTIONERROR,ResultType.SAVE_FAULT);
		}
		if(imgList != null&& imgList.size() > 0){
			imgMapper.batchInsert(product.getId(), imgList);
		}
		if(flag == 0) {
			throw new ServiceException(StatusCode.EXCEPTIONERROR,ResultType.SAVE_FAULT);
		}
		List<ProductParamEntity> paramList = product.getParamList();
		if(paramList!=null && paramList.size() > 0){
			for(ProductParamEntity param : paramList){
				if(param.getId() !=null ){
					flag = paramMapper.update(param);
					if(flag == 0) {
						throw new ServiceException(StatusCode.EXCEPTIONERROR,ResultType.SAVE_FAULT);
					}
				}else{
					param.setProductId(product.getId());
					flag = paramMapper.insert(param);
					if(flag == 0) {
						throw new ServiceException(StatusCode.EXCEPTIONERROR,ResultType.SAVE_FAULT);
					}
				}
			}
		}
		product.setUpdater(((BaseEntity)UserUtils.getCurrentUser()).getId());
		flag = productMapper.update(product);
		if(flag > 0){
			return Result.result(null, true, StatusCode.SAVESUCCESS, ResultType.SAVE_SUCCESS);
		}
		return null;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	@Transactional
	public Result batchDelete(String ids) {
		List<Map> idList =  JSONArray.parseArray(ids,Map.class);
		Result result = new Result();
		if(idList != null ){
			for(int i = 0 ; i < idList.size() ; i ++ ){
				Map<String,Object> idMap = (Map<String, Object>) idList.get(i);
				int skuId = (int) idMap.get("id");
				int productId = (int) idMap.get("productId");
				result = deleteProduct(Long.parseLong(productId+""), Long.parseLong(skuId+""), false);
				if(!result.isSuccess())
					break;
			}
		}
		return result ;
	}

	@Override
	public void findBaseProductInfo(PageUtils<ProductInfoVo> pageinfo) {
		long total = productMapper.findBaseProductCount(pageinfo);
		pageinfo.setTotal(total);
		if (total > 0) {
			pageinfo.setData(productMapper.findBaseProductInfo(pageinfo));
		} else {
			pageinfo.setData(new ArrayList<ProductInfoVo>());
		}
	}

	@Override
	public boolean find(Long proId, Long facId) {
		
		return productMapper.finds(proId, facId) > 0 ? true : false;
	}
	
	@Override
	public List<ProductSkuEntity> selectByProductNumber(String productNumber, Long facId,Long productId) {
		return productMapper.selectByProductNumber(productNumber, facId,productId);
	}

	@Override
	public List<ProductSkuVo> selectForOder(List<Map<String,Long>> skuIdList, Long ageId,String tableName) {
		return skuMapper.selectForOder(skuIdList, ageId,tableName);
	}


	
	
}
